package db

import (
	"fmt"
	"strconv"
	"strings"
)

type Video struct {
	Id       int
	Title    string
	Cover    string
	Url      string
	Year     string
	Director string
	Actor    string
	Type     string
	Intro    string
	Last     string
}

func AddVideo(video *Video) error {
	stmtIns, err := dbConn.Prepare(`INSERT INTO video (title, cover, url, year, director, actor, type, intro, last ) VALUES (?,?,?,?,?,?,?,?,?)`)

	if nil != err {
		return err
	}

	defer stmtIns.Close()

	_, err = stmtIns.Exec(video.Title, video.Cover, video.Url, video.Year,
		video.Director, video.Actor, video.Type, video.Intro, video.Last)

	return err
}

func RemoveDup() {

	rows, err := dbConn.Query("SELECT id,title FROM video WHERE title IN (\nSELECT v1.title FROM video v1 LEFT JOIN video v2 ON v1.title = v2.title AND v1.type = v2.type AND v1.last = v2.last AND v1.id != v2.id\n) ORDER BY title, id")

	if err != nil {
		fmt.Println(err)
	}

	defer rows.Close()

	var (
		videoId    int64
		deleteIds  []int64
		videoTitle string
	)
	titles := make(map[string]int64)

	for rows.Next() {
		_ = rows.Scan(&videoId, &videoTitle)

		if titles[videoTitle] != 0 {
			deleteIds = append(deleteIds, videoId)
		} else {
			titles[videoTitle] = videoId
		}
	}

	idNum := len(deleteIds)
	if idNum > 0 {

		var sb strings.Builder

		sb.WriteString("DELETE FROM video WHERE id IN (")

		for i, id := range deleteIds {
			if i == idNum-1 {
				sb.WriteString(strconv.FormatInt(id, 10) + ")")
			} else {
				sb.WriteString(strconv.FormatInt(id, 10) + ",")
			}
		}
		query := sb.String()

		_, err = dbConn.Exec(query)

		if err != nil {
			fmt.Println(err)
		}

	}

}
